import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import aiService from '@/services/aiService'
import { logger } from '@/utils/logger'

export const useAIStore = defineStore('ai', () => {
  // 状态
  const isDialogVisible = ref(false)
  const isLoading = ref(false)
  const currentFunction = ref('chat') // chat, explain, question, scenario
  const conversations = ref([])
  const error = ref(null)
  const floatingBallPosition = ref({ x: window.innerWidth - 80, y: window.innerHeight - 150 })
  const aiHealthStatus = ref(null)

  // 计算属性
  const hasConversations = computed(() => conversations.value.length > 0)
  const lastConversation = computed(() => 
    conversations.value.length > 0 ? conversations.value[conversations.value.length - 1] : null
  )

  // AI功能类型配置
  const functionConfig = {
    chat: {
      title: 'AI助手',
      icon: 'robot',
      placeholder: '请输入您的问题...',
      description: '智能法律助手，为您解答各种法律问题'
    },
    explain: {
      title: '条文解读',
      icon: 'book',
      placeholder: '请输入需要解读的条文内容...',
      description: '对法律条文进行通俗易懂的解释和举例说明'
    },
    question: {
      title: '法律问答',
      icon: 'question',
      placeholder: '请描述您遇到的法律问题...',
      description: '基于民法典为您提供专业的法律问题解答'
    },
    scenario: {
      title: '场景分析',
      icon: 'scenario',
      placeholder: '请描述具体的法律场景...',
      description: '分析法律场景，识别关键要点并提供建议'
    }
  }

  // Actions
  const showDialog = () => {
    isDialogVisible.value = true
    logger.userAction('打开AI对话框', { function: currentFunction.value })
  }

  const hideDialog = () => {
    isDialogVisible.value = false
    logger.userAction('关闭AI对话框')
  }

  const setCurrentFunction = (functionType) => {
    currentFunction.value = functionType
    logger.userAction('切换AI功能', { function: functionType })
  }

  const updateFloatingBallPosition = (position) => {
    floatingBallPosition.value = position
    // 保存位置到本地存储
    localStorage.setItem('ai-floating-ball-position', JSON.stringify(position))
  }

  const loadFloatingBallPosition = () => {
    const saved = localStorage.getItem('ai-floating-ball-position')
    if (saved) {
      try {
        floatingBallPosition.value = JSON.parse(saved)
      } catch (e) {
        logger.error('加载悬浮球位置失败:', e)
      }
    }
  }

  const addConversation = (conversation) => {
    conversations.value.push({
      id: Date.now(),
      timestamp: new Date().toISOString(),
      ...conversation
    })
    
    // 限制历史记录数量
    if (conversations.value.length > 50) {
      conversations.value = conversations.value.slice(-50)
    }
    
    // 保存到本地存储
    saveConversationsToLocal()
  }

  const clearConversations = () => {
    conversations.value = []
    localStorage.removeItem('ai-conversations')
    logger.userAction('清空AI对话历史')
  }

  const saveConversationsToLocal = () => {
    try {
      localStorage.setItem('ai-conversations', JSON.stringify(conversations.value))
    } catch (e) {
      logger.error('保存对话历史失败:', e)
    }
  }

  const loadConversationsFromLocal = () => {
    try {
      const saved = localStorage.getItem('ai-conversations')
      if (saved) {
        conversations.value = JSON.parse(saved)
      }
    } catch (e) {
      logger.error('加载对话历史失败:', e)
    }
  }

  const setError = (errorMessage) => {
    error.value = errorMessage
    logger.error('AI错误:', errorMessage)
  }

  const clearError = () => {
    error.value = null
  }

  // AI功能调用方法
  const explainArticle = async (articleContent) => {
    if (!articleContent.trim()) {
      throw new Error('请输入条文内容')
    }

    isLoading.value = true
    clearError()

    try {
      const result = await aiService.explainArticle(articleContent)
      
      const conversation = {
        type: 'explain',
        input: articleContent,
        output: result.explanation,
        success: true
      }
      
      addConversation(conversation)
      return result
    } catch (error) {
      const errorMessage = error.message || 'AI解读失败'
      setError(errorMessage)
      
      const conversation = {
        type: 'explain',
        input: articleContent,
        output: errorMessage,
        success: false
      }
      
      addConversation(conversation)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const answerQuestion = async (question) => {
    if (!question.trim()) {
      throw new Error('请输入您的问题')
    }

    isLoading.value = true
    clearError()

    try {
      const result = await aiService.answerQuestion(question)
      
      const conversation = {
        type: 'question',
        input: question,
        output: result.answer,
        success: true
      }
      
      addConversation(conversation)
      return result
    } catch (error) {
      const errorMessage = error.message || 'AI问答失败'
      setError(errorMessage)
      
      const conversation = {
        type: 'question',
        input: question,
        output: errorMessage,
        success: false
      }
      
      addConversation(conversation)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const getSearchSuggestions = async (query) => {
    if (!query.trim()) {
      throw new Error('请输入搜索关键词')
    }

    isLoading.value = true
    clearError()

    try {
      const result = await aiService.getSearchSuggestions(query)
      
      const conversation = {
        type: 'suggestions',
        input: query,
        output: result.suggestions.join(', '),
        success: true,
        suggestions: result.suggestions
      }
      
      addConversation(conversation)
      return result
    } catch (error) {
      const errorMessage = error.message || '获取搜索建议失败'
      setError(errorMessage)
      
      const conversation = {
        type: 'suggestions',
        input: query,
        output: errorMessage,
        success: false
      }
      
      addConversation(conversation)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const analyzeScenario = async (scenario) => {
    if (!scenario.trim()) {
      throw new Error('请描述具体的法律场景')
    }

    isLoading.value = true
    clearError()

    try {
      logger.info('开始AI场景分析', { scenario: scenario.substring(0, 50) + '...' })
      const result = await aiService.analyzeScenario(scenario)
      
      logger.info('AI场景分析响应', { 
        hasAnalysis: !!result.analysis,
        hasFeedback: !!result.feedback,
        analysis: result.analysis,
        feedback: result.feedback
      })
      
      // 场景分析需要更多信息
      if (result.feedback && result.feedback.type === 'MORE_INFO_NEEDED') {
        const conversation = {
          type: 'scenario',
          input: scenario,
          output: result.feedback.message,
          success: true, // API调用成功，但需要用户反馈
          feedback: result.feedback,
          analysis: null
        }
        addConversation(conversation)
        return result
      }
      
      // 验证analysis结构
      if (!result.analysis) {
        logger.error('AI返回缺少analysis字段', result)
        throw new Error('AI返回数据格式错误')
      }
      
      const conversation = {
        type: 'scenario',
        input: scenario,
        output: JSON.stringify(result.analysis, null, 2),
        success: true,
        analysis: result.analysis,
        feedback: null
      }
      
      logger.info('保存场景分析对话', { 
        conversationType: conversation.type,
        hasKeyPoints: !!conversation.analysis?.key_points,
        keyPointsLength: conversation.analysis?.key_points?.length,
        hasArticles: !!conversation.analysis?.related_articles,
        articlesLength: conversation.analysis?.related_articles?.length,
        hasAdvice: !!conversation.analysis?.preliminary_advice
      })
      
      addConversation(conversation)
      return result
    } catch (error) {
      logger.error('AI场景分析失败', error)
      const errorMessage = error.message || 'AI场景分析失败'
      setError(errorMessage)
      
      const conversation = {
        type: 'scenario',
        input: scenario,
        output: errorMessage,
        success: false,
        analysis: null,
        feedback: null
      }
      
      addConversation(conversation)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const checkAIHealth = async () => {
    try {
      const result = await aiService.checkHealth()
      aiHealthStatus.value = result
      return result
    } catch (error) {
      logger.error('AI健康检查失败:', error)
      aiHealthStatus.value = { success: false, status: 'unhealthy' }
      throw error
    }
  }

  // 初始化
  const initialize = () => {
    loadFloatingBallPosition()
    loadConversationsFromLocal()
    checkAIHealth()
  }

  return {
    // 状态
    isDialogVisible,
    isLoading,
    currentFunction,
    conversations,
    error,
    floatingBallPosition,
    aiHealthStatus,
    
    // 计算属性
    hasConversations,
    lastConversation,
    
    // 配置
    functionConfig,
    
    // Actions
    showDialog,
    hideDialog,
    setCurrentFunction,
    updateFloatingBallPosition,
    loadFloatingBallPosition,
    addConversation,
    clearConversations,
    setError,
    clearError,
    
    // AI功能
    explainArticle,
    answerQuestion,
    getSearchSuggestions,
    analyzeScenario,
    checkAIHealth,
    
    // 初始化
    initialize
  }
})

